package com.nci.cloud.unit.management.ProtoBufFileTrans;

import com.google.protobuf.ByteString;
import com.nci.cloud.unit.management.message.Message;
import io.netty.channel.ChannelHandlerContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileUploadUtils {
    final static int PARTITIONSIZE =1* 1024*1024; // 1M 大小一个包

    public static void fileUpload(String userName ,String passwd ,String fileName,ChannelHandlerContext channel){
        File file  = new File(fileName);
        Message.TransRequest.Builder builder =  Message.TransRequest.newBuilder();
        builder.setCommand(Message.commandType.upload);
        builder.setUser(fileName);
        builder.setPasswd(passwd);
        builder.setTimestamp(System.currentTimeMillis());
        FileInputStream fis = null;
        try {
            Message.TransFileContent.Builder contentBuilder =  Message.TransFileContent.newBuilder();
            contentBuilder.setFilename(file.getName()); // file name 1
            contentBuilder.setFileSize(file.length()); // file size 4
            int partitionNum = (int) (file.length()/PARTITIONSIZE); // partition 2
            if (partitionNum <1){partitionNum = 1;}
            if(partitionNum>1&&file.length()%PARTITIONSIZE!=0){
                partitionNum = partitionNum+1;
            }
            contentBuilder.setPartitionNum(partitionNum);
            fis = new FileInputStream(file);
            byte[] readContent  = null;
            if(file.length()<PARTITIONSIZE){
                readContent = new byte[(int)file.length()];
            }// if
            else{
                readContent= new byte[PARTITIONSIZE];
            }// else
            int partitionNo = 1;
            long restLength = file.length();
            while(fis.read(readContent)>0){
                contentBuilder.setPartition(partitionNo); //partition 3
                partitionNo++;
                contentBuilder.setPartitionSize(readContent.length); // partition size 5
                ByteString content = ByteString.copyFrom(readContent);
                contentBuilder.setFileContent(content); // content 6
                contentBuilder.setContentHash(ByteToMd5Util.bytesToHexString(readContent)); // content hash 7
                builder.setContent(contentBuilder);
                // write and flush
                channel.writeAndFlush(builder.build());
                restLength = restLength - readContent.length;
                readContent = null;
                if(restLength>PARTITIONSIZE){
                    readContent= new byte[PARTITIONSIZE];
                }// if
                else{
                    readContent = new byte[(int)restLength];
                }// else
            }// while
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }// fileUpload

}
